{extend name="default:layout:base" /}

{block name="main"}
<div class="layui-tab layui-tab-brief" lay-filter="{$controller}-tab">
    {notempty name="tab_nav"}
    <ul class="layui-tab-title">
        {volist name="tab_nav.tab_list" id="tab"}
        <li class="{if $key eq $tab_nav['current_tab']}layui-this{/if}"><a href="{$tab.href}">{$tab.title}</a></li>
        {/volist}
    </ul>
    {/notempty}
    <div class="layui-tab-content">
        {if condition="!empty($tip)"}
        <blockquote class="layui-elem-quote">{$tip|raw}</blockquote>
        {/if}

        {notempty name="search"}
        <fieldset class="table-search-fieldset" style="padding: 0;">
            <div>
                <form class="layui-form layui-form-pane" id="search-{$controller}">
                    <div class="layui-form-item" style="margin: 5px">
                        {foreach $search as $v}
                        {switch name="v.type" }
                        {case btn_group}
                        <!--按钮组-->
                        <div class="layui-inline" lay-filter="filter-{$v.name}">
                            <div class="layui-input-inline" style="width: auto;">
                                <div class="layui-btn-group">
                                    {volist name="v.options" id="o"}
                                    <button type="button"
                                            class="js-btngroup-{$v.name} layui-btn {:isset($v.value) && $v.value == $key ? 'layui-btn-normal' : 'layui-btn-primary'}"
                                            data-value="{$key}"
                                    >{$o}</button>
                                    {/volist}
                                </div>
                                <input type="hidden" name="{$v.name}" id="btn_group-{$v.name}">
                            </div>
                            <script>
                                layui.use(['jquery'], function (){
                                    var $ = layui.jquery;
                                    $(".js-btngroup-{$v.name}").on('click', function () {
                                        $('.js-btngroup-{$v.name}').addClass("layui-btn-primary").removeClass('layui-btn-normal');
                                        $(this).addClass("layui-btn-normal").removeClass("layui-btn-primary");
                                        $("#btn_group-{$v.name}").val($(this).data('value'));

                                        $('button[lay-filter="data-search-btn"]').trigger('click');
                                    });
                                });
                            </script>
                        </div>
                        {/case}
                        {case linkage}
                        <!--下拉框联动-->
                        <div class="layui-form-item" lay-filter="filter-{$v.name}">
                            <label class="layui-form-label">{$v['title']}</label>
                            <div class="layui-input-block" id="linkage-{$v.name}"></div>
                            <script>
                                layui.use(['selectN'], function () {
                                    var selectN = layui.selectN;
                                    var cateData = {:json_encode($v.options.data)}
                                , selectedData = {:json_encode(empty($v['options']['values']) ? [] : $v['options']['values'])}
                                , tips = {if empty($v['options']['tips'])}"请选择"{else/}{:json_encode($v['options']['values'])}{/if};

                                    //无限级分类-所有配置
                                    var catIns2 = selectN({
                                        //元素容器【必填】
                                        elem: '#linkage-{$v.name}'
                                        //候选数据【必填】
                                        , data: cateData
                                        //设置了长度
                                        , width: null
                                        //默认值
                                        , selected: selectedData
                                        , search: true
                                        , tips: tips
                                        , name: '{$v.name}'
                                        , delimiter: ','
                                        , field: {idName: 'id', titleName: 'title', childName: 'children'}
                                    });

                                });
                            </script>
                        </div>
                        {/case}
                        {case datetime_range}
                        <div class="layui-inline">
                            <label class="layui-form-label">{$v.title}</label>
                            <div class="layui-input-inline" style="width: 290px;">
                                <input type="text" id="{$v.name}" name="{$v.name}" value="" class="layui-input" placeholder="{$v.placeholder ?? $v.title}">
                            </div>
                        </div>
                        <script>
                            layui.use(['laydate'], function() {
                                var laydate = layui.laydate;

                                //执行一个laydate实例
                                laydate.render({
                                    elem: '#{$v.name}'
                                    , type: 'datetime'
                                    , max: 1 //7天后
                                    , range: '~'
                                });
                            });
                        </script>
                        {/case}
                        {case select}
                        <div class="layui-inline">
                            <label class="layui-form-label">{$v.title}</label>
                            <div class="layui-input-inline">
                                <select name="{$v.name}">
                                    {volist name="v.options" id="o"}
                                    <option value="{$key}">{$o}</option>
                                    {/volist}
                                </select>
                            </div>
                        </div>
                        {/case}
                        {default /}
                        <div class="layui-inline">
                            <label class="layui-form-label">{$v.title}</label>
                            <div class="layui-input-inline">
                                <input type="text" name="{$v.name}" autocomplete="off" class="layui-input" placeholder="{$v.placeholder ?? $v.title}" value="{$v.value??''}">
                            </div>
                        </div>
                        {/switch}
                        {/foreach}
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary"  lay-submit lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索</button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>
        {/notempty}

        {notempty name="top_button_list"}
        <script type="text/html" id="top-btns">
            {foreach $top_button_list as $button}
            <button type="button" {$button['attribute']|raw} >{$button['text']??$button['title']}</button>&nbsp;
            {/foreach}
        </script>
        {/notempty}

        <table class="layui-hide" id="{$controller}-table" lay-filter="{$controller}-table"></table>

        {notempty name="right_button_list"}
        <script type="text/html" id="right-btns">
            {if count($right_button_list) > 3}
            <div class="layui-row table-ops">
                <div class="layui-col-xs8 text-right">
                    <div class="layui-btn-group">
                        {foreach $right_button_list as $k => $button}
                        {if $k < 2}
                        <button type="button" {$button['attribute']|raw} >{$button['text']??$button['title']}</button>&nbsp;
                        {/if}
                        {/foreach}
                    </div>
                </div>
                <div class="layui-col-xs4 text-left">
                    <ul class="layui-menu">
                        <li class="layui-menu-item-group layui-menu-item-up">
                            <div class="layui-menu-body-title layui-btn layui-btn-xs layui-btn-primary">
                                更多<i class="layui-icon layui-icon-down"></i>
                            </div>
                            <ul>
                                {foreach $right_button_list as $k => $button}
                                {if $k > 1}
                                <li><button type="button" {$button['attribute']|raw} >{$button['text']??$button['title']}</button></li>
                                {/if}
                                {/foreach}
                            </ul>
                        </li>
                    </ul>
                </div>
            </div>
            {else/}
            <div class="layui-btn-group">
                {foreach $right_button_list as $button}
                <button type="button" {$button['attribute']|raw} >{$button['text']??$button['title']}</button>&nbsp;
                {/foreach}
            </div>
            {/if}
        </script>
        {/notempty}
    </div>
</div>

<style>
    .table-ops .layui-menu{margin: 0;background: none;}
    .table-ops .layui-menu li{padding: 0;line-height: 20px;}
    .table-ops .layui-menu .layui-menu-item-group > ul{margin: 0;}
    .table-ops .layui-menu-item-group .layui-menu-body-title{padding-right: 15px;color: #666;}
    .layui-table-total{padding: 8px;}
</style>
{notempty name="css"}
<style>
    {$css|raw}
</style>
{/notempty}

<script>
    layui.use(['form', 'table', 'element', 'miniTab', 'jquery'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table,
        miniTab = layui.miniTab;

        var cols = {:json_encode($table_column_list)};
        var table_data_page = {:json_encode($table_data_page)};
        var list_limit = table_data_page == null ? 15 : table_data_page.limit;
        cols = cols.map((item, i) => {
            switch(item.type){
                case 'switch':
                    var layText = item.text ? item.text : "启用|禁用";
                    item = Object.assign(item, {templet: function (d) {
                            console.log(d);
                            let val = d[item.field]
                            return `<input type="checkbox" value="${val}" data-id="${d.id}" lay-skin="switch" lay-text="${layText}" lay-filter="{$controller}-switch"
           `+(val ? "checked" : "")+`>`
                        }});
                    break;
                case 'array':
                    item = Object.assign(item, {templet: function (d) {
                            return "<div>"+d[item.field].join(',')+"</div>";
                        }});
                    break;
                case 'article':
                    item = Object.assign(item, {templet: function (d) {
                            return templets.article(d[item.field]);
                        }});
                    break;
                case 'pre':
                    item = Object.assign(item, {templet: function (d) {
                            return "<pre>"+d[item.field]+"</pre>";
                        }});
                    break;
                case 'index':
                    item = Object.assign(item, {minWidth: 50,templet: function (d) {
                            return d.LAY_TABLE_INDEX + 1;
                        }});
                    break;
                case 'enum':
                    var options = item.options;
                    item = Object.assign(item, {templet: function (d) {
                            return options.hasOwnProperty(d[item.field]) ? options[d[item.field]] : '--';
                        }});
                    break;
                case 'video':
                    item = Object.assign(item, {templet: function (d) {
                            return templets.video(d[item.field]);
                        }});
                    break;
                case 'price':
                    item = Object.assign(item, {templet: function (d) {
                            return (parseInt(d[item.field]) / 100).toFixed(2);
                        }});
                    break;
                case 'pay_status':
                    var status = ['未支付', '已支付', '已退款'];
                    item = Object.assign(item, {templet: function (d) {
                            return status[d[item.field]];
                        }});
                    break;
                case 'datetime':
                    item = Object.assign(item, {templet: function (d) {
                            return d[item.field] > 0 ? tools.timeChange(d[item.field], 'timestamp','Y-m-d H:i:s') : '--';
                        }});
                    break;
                case 'yesorno':
                    item = Object.assign(item, {templet: function (d) {
                            return d[item.field] ? '是' : '否';
                        }});
                    break;
                case 'picture':
                    item = Object.assign(item, {templet: function (d) {
                        return templets.picture(d[item.field]);
                    }});
                    break;
                case 'toolbar':
                    item = Object.assign(item, {toolbar: '#right-btns', align: "center",fixed: 'right'});
                    break;
            }
            return item;
        });

        var tt = table.render({
            elem: '#{$controller}-table',
            url: '{:empty($data_url) ? url($action, request()->get()) : $data_url}',
            toolbar: '#top-btns',
            method: 'post',
            cols: [cols],
            limits: [10, 15, 20, 25, 50, 100],
            limit: list_limit,
            page: true,
            skin: 'line',
            loading: true,
            autoSort: false,
            defaultToolbar: [{
                        layEvent: 'refresh',
                        icon: 'layui-icon-refresh',
                    }, 'filter', 'print', 'exports'],
            parseData: function(res){ //res 即为原始返回的数据
                return {
                    "code": Math.abs(res.code - 1), //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.list, //解析数据列表
                    "extra": res.data
                };
            },
            text: {
                none: kyDicts.emptyData
            },
            done: function(res, curr, count){
                if(res.totalRow && res.code === 0 && this.page.curr <= 1){
                    var extra = res.extra;
                    $.post(extra.total_row_url, {where: extra.total_row_where}, function(r){
                        if(r.code === 1){
                            $('.layui-table-total').html(r.data.total_row_text).removeClass('hide');
                        }else{
                            layer.alert(r.msg);
                        }
                    }, 'json').error(function (xhr, status, info) {
                        layer.alert('系统繁忙，请刷新重试或联系管理员');
                    });
                }
                if(window.table && typeof window.table.done === 'function'){
                    window.table.done(res, curr, count);
                }
            }
        });

        //状态开关
        form.on('switch({$controller}-switch)', function(obj) {
            let href = "{:url('setstatus')}",
                    data  = {ids: $(this).data('id'), val: obj.value}
            layer.confirm("确认操作吗？", function(index){
                requestPost(href, data, function (res) {
                    table.reload('{$controller}-table');  // 刷新(异步模式)
                    form.render('switch');
                });
                layer.close(index);
            });
        });
        {notempty name="search"}
        formToggle({
            elem: "#search-{$controller}",
        });
        //展开|折叠
        function formToggle(options) {
            var defaultsOpt = {
                isExpand: false,
                prefixIcon: "layui-icon",
                toggleIcon: ['layui-icon-down', 'layui-icon-up'],
                toggleText: ['展开', '折叠'],
            }
            var opt = $.extend({}, defaultsOpt, options);
            var elem = opt.elem; // 绑定的表单元素,必填
            var min = opt.min; // 最小显示数,默认显示一行
            var isExpand = opt.isExpand; // 初始展开
            var prefixIcon = opt.prefixIcon + " "; // 图标前缀
            var toggleIcon = opt.toggleIcon; // 折叠和展开时的图标类[unExpandIcon, ExpandIcon]
            var toggleText = opt.toggleText; // 折叠和展开时的文本

            var eleDOM = $(elem + " .layui-inline");
            var firstElTop = eleDOM.first().offset().top;
            var targetEl = eleDOM.filter(function(index) {
                var isGtMin = (index + 1) > min;
                var isGtFirstElTop = $(this).offset().top > firstElTop;
                var isNeqLast = (index + 1) != eleDOM.length;
                return min ? isGtMin && isNeqLast : isGtFirstElTop && isNeqLast;
            });

            var unExpandIcon = prefixIcon + toggleIcon[0];
            var expandIcon = prefixIcon + toggleIcon[1];
            var unExpandText = toggleText[0];
            var expandText = toggleText[1];
            var btnSelector = elem + " .expand";
            $(btnSelector).append("<i></i>")

            if (targetEl.length > 0) {
                if (isExpand) {
                    $(btnSelector).prepend("<span>" + expandText + "</span>");
                    $(btnSelector + ">i").addClass(expandIcon);
                } else {
                    $(btnSelector).prepend("<span>" + unExpandText + "</span>")
                    $(btnSelector + ">i").addClass(unExpandIcon)
                    targetEl.addClass("layui-hide");
                }
                $(btnSelector).click(function() {
                    isExpand = !isExpand;
                    if (isExpand) {
                        $(btnSelector + ">span").html(expandText);
                        $(btnSelector + ">i").removeClass(unExpandIcon).addClass(expandIcon);
                        targetEl.removeClass("layui-hide")
                    } else {
                        $(btnSelector + ">span").html(unExpandText);
                        $(btnSelector + ">i").removeClass(expandIcon).addClass(unExpandIcon);
                        targetEl.addClass("layui-hide")
                    }
                })
            }
        }
        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            tt.config.where = data.field;
            //执行搜索重载
            table.reload('{$controller}-table', {
                page: {
                    curr: 1
                }
                , where: data.field
            }, 'data');
            return false;
        });
        {/notempty}

        {notempty name="top_button_list"}
        //顶部按钮监听事件
        table.on('toolbar({$controller}-table)', function (obj) {
            var href = $(this).attr('href')
            , title = $(this).attr('title');

            switch (obj.event) {
                case 'refresh':
                    table.reload('{$controller}-table');
                    break;
                case 'add':
                    var index = layer.open({
                        title: title,
                        type: 2,
                        shade: 0.2,
                        maxmin:true,
                        area: ['95%', '95%'],
                        content: href,
                    });
                    $(window).on("resize", function () {
                        layer.full(index);
                    });
                    return false;
                case 'delete':
                        layer.confirm('确认删除?',{title:'温馨提示'}, function(index){
                            var ids = table.checkStatus('{$controller}-table').data.map((item,index) => {return item.id});
                            var params = {ids: ids};
                            requestPost(href, params, function (res) {
                                table.reload('{$controller}-table');  // 刷新(异步模式)
                            });
                            layer.close(index);
                        });
                        break;
                case 'forbid':
                    layer.confirm('确认批量禁用吗?', function(index){
                        var ids = table.checkStatus('{$controller}-table').data.map((item,index) => {return item.id});
                        var params = {ids: ids};
                        requestPost(href, params, function (res) {
                            table.reload('{$controller}-table');  // 刷新(异步模式)
                        });
                        layer.close(index);
                    });
                    break;
                case 'self':
                    if($(this).data('ajax')){
                        if($(this).data('confirm')) {
                            layer.confirm('确认操作吗?', function(index){
                                var ids = table.checkStatus('{$controller}-table').data.map((item,index) => {return item.id});
                                var params = {ids: ids};
                                requestPost(href, params, function (res) {
                                    table.reload('{$controller}-table');  // 刷新(异步模式)
                                });
                                layer.close(index);
                            });
                        }else{
                            requestPost(href, [], function (res) {
                                table.reload('{$controller}-table');  // 刷新(异步模式)
                            });
                        }
                    }else{
                        var target = $(this).attr('target');
                        switch (target) {
                            case '_blank':
                                window.open(href);
                                break;
                            case '_self':
                                location.href = href;
                                break;
                            default:
                                miniTab.openNewTabByIframe({
                                    href: href,
                                    title: $(this).attr('title'),
                                });
                        }
                    }
                    break;
            }
        });
        {/notempty}
            //触发排序事件
            table.on('sort({$controller}-table)', function(obj){
                table.reload('{$controller}-table', {
                    page: {
                        curr: 1
                    }
                    , where: Object.assign(tt.config.where, {
                        order_field: obj.field //排序字段
                        ,order_type: obj.type //排序方式
                    })
                }, 'data');
                return false;
            });

        {notempty name="right_button_list"}
        //监听操作栏按钮
        table.on('tool({$controller}-table)', function (obj) {
            var data = obj.data
            , layEvent = obj.event
                , title = $(this).attr('title')
            , href = $(this).attr('href').replace('__data_id__', data.id);
            for (var k in data){
                href = href.replaceAll(`__data_${k}__`, data[k])
            }

            switch (layEvent) {
                case 'appConsole':
                    if(! data.admin_url){
                        layer.msg("无需配置");
                        return false;
                    }
                    if(data.admin_url_type === 1){
                        miniTab.openNewTabByIframe({
                            href: data.admin_url,
                            title: '应用配置',
                        });
                    }else{
                        window.open(data.admin_url);
                    }
                    return false;
                case 'edit':
                    var index = layer.open({
                        title: title,
                        type: 2,
                        shade: 0.2,
                        area: ['95%', '95%'],
                        content: href,
                    });
                    $(window).on("resize", function () {
                        layer.full(index);
                    });
                    return false;
                case 'forbid':
                    var tip = $(this).attr('confirm') ? $(this).attr('confirm') : "确认批量禁用吗？";
                    layer.confirm(tip, function(index){
                        var  params = {ids: data.id};
                        requestPost(href, params, function (res) {
                            table.reload('{$controller}-table');  // 刷新(异步模式)
                        });
                        layer.close(index);
                    });
                    break;
                case 'resume':
                    var tip = $(this).attr('confirm') ? $(this).attr('confirm') : "确认批量启用吗？";
                    layer.confirm(tip, function(index){
                        var  params = {ids: data.id};
                        requestPost(href, params, function (res) {
                            table.reload('{$controller}-table');  // 刷新(异步模式)
                        });
                        layer.close(index);
                    });
                    break;
                case 'delete':
                    layer.confirm('确认'+title+'?',{title:'温馨提示'}, function(index){
                        var  params = {ids: data.id};
                        requestPost(href, params, function (res) {
                            table.reload('{$controller}-table');  // 刷新(异步模式)
                        });
                        layer.close(index);
                    });
                    break;
                case 'self':
                    if($(this).data('ajax')){
                        if($(this).data('confirm')) {
                            var tip = $(this).data('confirm');
                            if(typeof tip !== "string"){
                                tip = '确认操作吗?';
                            }
                            layer.confirm(tip, function(index){
                                var  params = {id: data.id};
                                requestPost(href, params, function (res) {
                                    table.reload('{$controller}-table');  // 刷新(异步模式)
                                });
                                layer.close(index);
                            });
                        }else{
                            requestPost(href, [], function (res) {
                                table.reload('{$controller}-table');  // 刷新(异步模式)
                            });
                        }
                    }else{
                        var target = $(this).attr('target');
                        switch (target) {
                            case '_blank':
                                window.open(href);
                                break;
                            case '_self':
                                location.href = href;
                                break;
                            default:
                                miniTab.openNewTabByIframe({
                                    href: href,
                                    title: $(this).attr('title'),
                                });
                        }
                    }
                    break;
            }
        });
        {/notempty}
        });
</script>
{/block}